package com.wuhuahe.learning.lagou.service.code.service.impl;

import com.wuhuahe.learning.lagou.service.code.mapper.CodeMapper;
import com.wuhuahe.learning.lagou.service.code.pojo.Code;
import com.wuhuahe.learning.lagou.service.code.service.CodeService;
import com.wuhuahe.learning.lagou.service.common.exception.CodeException;
import com.wuhuahe.learning.lagou.service.common.exception.CreateCodeException;
import com.wuhuahe.learning.lagou.service.common.exception.SendCodeException;
import com.wuhuahe.learning.lagou.servie.feign.api.EmailFeignApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Random;

@Service
public class CodeServiceImpl implements CodeService {

    private static final Logger logger = LoggerFactory.getLogger(CodeServiceImpl.class);

    @Resource
    private CodeMapper codeMapper;

    @Resource
    private EmailFeignApi emailFeignApi;

    @Override
    public Code createCode(String email)  throws CodeException {
        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(random.nextInt(10));
        }
        String code = stringBuilder.toString();
        Code codePojo = new Code();
        codePojo.setCode(code);
        codePojo.setEmail(email);
        Calendar now = Calendar.getInstance();
        codePojo.setCreatetime(new Timestamp(now.getTime().getTime()));
        now.add(Calendar.MINUTE, 10);
        codePojo.setExpiretime(new Timestamp(now.getTime().getTime()));
        try{
            int codeId = codeMapper.insertCode(codePojo);
            codePojo.setId(codeId);
        } catch (Exception e){
            throw new CreateCodeException(e.getMessage());
        }


        // 发送邮件
        boolean sendEmail = emailFeignApi.email(email, code);
        logger.info("验证码邮件发送结果：" + (sendEmail ? "成功" : "失败"));
        if(!sendEmail){
            throw new SendCodeException("发送验证码邮件失败");
        }


        return codePojo;
    }

    @Override
    public int validate(String email, String code) throws CodeException {
        Code latestCodeByEmail = codeMapper.getLatestCodeByEmailAndCode(email, code);
        if(latestCodeByEmail == null) {
            // 不存在，则认为错误
            return 1;
        }
        Timestamp expiretime = latestCodeByEmail.getExpiretime();
        if(expiretime.getTime() < System.currentTimeMillis()){
            // 超时
            return 2;
        }
        return 0;
    }
}
